<template>
  <div class="container" ref="container"></div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

const container = ref();

// Our Javascript will go here.
// 创建场景
const scene = new THREE.Scene();
// 改变场景的背景-颜色
scene.background = new THREE.Color(0x666666);

// 创建相机
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
// 调整相机位置
camera.position.z = 2;
camera.position.y = 5;

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });

// 创建一个三维向量
// const vector = new THREE.Vector3(1, 1, 1);

const cube = new THREE.Mesh(geometry, material);
// 位置移动
// cube.position.set(0, 0.5, 0);
// cube.position.y = 0.5;
// cube.position.add(vector) // 在现在的基础上累加
// cube.position.addScalar(0.5);

// 局部缩放
// cube.scale.set(2, 1, 1);

// 平移
// cube.translateX(1);

// 显示与隐藏
// cube.visible = true;

// 分组
const cubeA = new THREE.Mesh(geometry, material);
cubeA.position.set(5, 5, 0);

const cubeB = new THREE.Mesh(geometry, material);
cubeB.position.set(-5, -5, 0);

const group = new THREE.Group();
group.add(cubeA);
group.add(cubeB);

scene.add(group);
scene.add(cube);

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
// 调整渲染器窗口大小
renderer.setSize(window.innerWidth, window.innerHeight);

// 添加一个网格地面
const gridHepler = new THREE.GridHelper(10, 10);
scene.add(gridHepler);

// 在页面中添加元素
onMounted(() => {
  // 将渲染节点添加到页面
  container.value.appendChild(renderer.domElement);
});

// 添加轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);

// 开启阻尼效果 （视角拖动的时候会有惯性）
controls.enableDamping = true; // 开启
controls.dampingFactor = 0.05; // 阻尼惯性大小

// 添加坐标轴
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

// 让立方体动起来
function animate() {
  requestAnimationFrame(animate);

  // 轨道控制器更新
  controls.update();
  // 调用渲染器进行渲染
  renderer.render(scene, camera);
}

animate();
</script>

<style>
* {
  margin: 0;
}
html,
body {
  width: 100vw;
  height: 100vh;
}

.container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.buttons {
  left: 20px;
  position: fixed;
  top: 20px;
}

#gui {
  position: absolute;
  right: 0;
  width: 300px;
}
</style>
